import request from '@/utils/request'

// Base URL for telecom API endpoints
const BASE_URL = "/telecom/api";

// City region code mapping
const REGION_CODE_MAP = {
  广州: "200",
  佛山: "757",
  东莞: "769",
  惠州: "752",
  江门: "750",
  湛江: "759",
};

// Get phone location information
export function getPhoneLocation(phoneNumber) {
  return request({
    url: `/phone-api/phonearea.php?number=${phoneNumber}`,
    method: 'get'
  })
}

// Check if it is a supported city
export function isSupportedCity(city) {
  return city in REGION_CODE_MAP;
}

// Get region code by city name
export function getRegionCode(city) {
  if (!isSupportedCity(city)) {
    throw new Error("暂不支持该号码归属地的业务办理");
  }
  return REGION_CODE_MAP[city];
}

// Get client IP address
export async function getClientIp() {
  try {
    const response = await fetch('https://api.ipify.org?format=json');
    const data = await response.json();
    return data.ip;
  } catch (error) {
    console.error("获取 IP 地址失败:", error);
    return "127.0.0.1";
  }
}

// Get URL parameter
export function getUrlParam(name) {
  const url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
  const results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return "";
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// Send SMS verification code
export async function sendSmsCode(mobileNo) {
  try {
    // Get phone location
    const locationResponse = await getPhoneLocation(mobileNo);
    const locationInfo = locationResponse.data;
    
    if (locationResponse.code !== 0) {
      throw new Error("获取手机号归属地失败");
    }
    
    const city = locationInfo.city;

    // Check carrier
    if (locationInfo.sp !== "电信") {
      throw new Error("该号码非中国电信号码，暂不支持办理");
    }

    const userAgent = window.navigator.userAgent;
    const requestData = {
      channelNo: "HNYZ", // Replace with actual channel number
      productNo: "ZH-30Y15GLLB", // Replace with actual product code
      regionCode: getRegionCode(city),
      mobileNo,
      orderInfo: {
        ua: userAgent,
        ip: await getClientIp(),
        appName: "appName",
        appPackage: "com.example.app",
        platform: "platform",
        platformCode: "xx",
        voucherNo: "",
        link: window.location.href,
      },
    };

    return request({
      url: `${BASE_URL}/business/sms/send`,
      method: 'post',
      data: requestData
    });
  } catch (error) {
    console.error("发送验证码失败:", error);
    throw error;
  }
}

// Create order
export async function createOrder(mobileNo, smsCode, extendData) {
  try {
    // Get phone location
    const locationResponse = await getPhoneLocation(mobileNo);
    const locationInfo = locationResponse.data;
    
    if (locationResponse.code !== 0) {
      throw new Error("获取手机号归属地失败");
    }
    
    const city = locationInfo.city;

    // Check carrier
    if (locationInfo.sp !== "电信") {
      throw new Error("该号码非中国电信号码，暂不支持办理");
    }

    const userAgent = window.navigator.userAgent;
    const requestData = {
      channelNo: "HNYZ", // Replace with actual channel number
      productNo: "ZH-30Y15GLLB", // Replace with actual product code
      regionCode: getRegionCode(city),
      mobileNo,
      smsCode,
      extendData,
      orderInfo: {
        ua: userAgent,
        ip: await getClientIp(),
        appName: "",
        appPackage: "",
        platform: "",
        platformCode: "",
        link: window.location.href,
      },
    };

    const result = await request({
      url: `${BASE_URL}/business/order/create`,
      method: 'post',
      data: requestData
    });

    // If order created successfully, report conversion to ByteDance (no need to wait for response)
    if (result.code === 200) {
      reportConversion();
    }

    return result;
  } catch (error) {
    console.error("创建订单失败:", error);
    throw error;
  }
}

// Report conversion to ByteDance
export function reportConversion() {
  try {
    // Get clickid from URL
    const clickid = getUrlParam("clickid");
    if (!clickid) {
      console.warn("未找到clickid参数，无法回传转化数据");
      return;
    }

    const requestData = {
      event_type: "active",
      context: {
        ad: {
          callback: clickid,
        },
      },
      timestamp: Date.now(),
    };

    // Send POST request to ByteDance, don't wait for response
    request({
      url: '/api/v2/conversion',
      method: 'post',
      data: requestData
    }).then(response => {
      console.log("转化数据回传成功:", response);
    }).catch(error => {
      console.error("转化数据回传失败:", error);
    });

    // Don't return anything, don't block main flow
  } catch (error) {
    console.error("转化数据回传失败:", error);
    // Just log error, don't throw exception to avoid affecting main flow
  }
} 